package com.sh.utils;


import com.sh.bean.CommonInformationItem;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class RssDataGrab extends DefaultHandler {
    private static Logger log = Logger.getLogger(RssDataGrab.class.getName());
    public List<CommonInformationItem> list;  // 定义一个List集合，用于存放解析出来的数据
    private CommonInformationItem item;  // 定义一个对象，用于存放解析出来的数据
    private StringBuffer buffer;  // 存节点里面的文本的暂时变量
    private DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);  // 定义一个日期格式化对象
    private int status;  // 当前是什么标记
    private String source;  // 就是名字
    private final int STATUS_TITLE = 1;
    private final int STATUS_LINK = 2;
    private final int STATUS_DESCRIPTION = 3;
    private final int STATUS_PUBDATE = 4;
    private final int STATUS_GUID = 5;

    public RssDataGrab(String name) {
        this.source = name;   // 初始化名字
        this.buffer = new StringBuffer();
    }


    public List<CommonInformationItem> load(String source) {
        list = new ArrayList<>();
        try {
            // 1. 获取解析器工厂
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 2. 获取解析器
            SAXParser parser = spf.newSAXParser();
            // 3. 开始解析
            parser.parse(source, this);
        } catch (Exception e) {
            log.error("解析RSS数据出错", e);
            e.printStackTrace();
        }
        // 4. 结束解析
        return list;
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//        System.out.println("开始解析RSS数据xml元素开头" + "  uri: " + uri + "   localName: " + localName + "   qName: " + qName + "   attributes: " + attributes);
        if (item != null && qName.equalsIgnoreCase("title")) {
            status = STATUS_TITLE;
        } else if (item != null && qName.equalsIgnoreCase("link")) {
            status = STATUS_LINK;
        } else if (item != null && qName.equalsIgnoreCase("description")) {
            status = STATUS_DESCRIPTION;
        } else if (item != null && qName.equalsIgnoreCase("pubDate")) {
            status = STATUS_PUBDATE;
        } else if (item != null && qName.equalsIgnoreCase("guid")) {
            status = STATUS_GUID;
        } else if (qName.equalsIgnoreCase("item")) {
            item = new CommonInformationItem();
            item.setSource(source);
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
//        System.out.println("开始解析RS数据xml元素结尾" + "  uri: " + uri + "   localName: " + localName + "   qName: " + qName);
        if (item != null && qName.equalsIgnoreCase("title")) {
            item.setTitle(buffer.toString());
        } else if (item != null && qName.equalsIgnoreCase("link")) {
            item.setLink(buffer.toString());
        } else if (item != null && qName.equalsIgnoreCase("description")) {
            item.setDescription(buffer);
        } else if (item != null && qName.equalsIgnoreCase("pubDate")) {
            item.setTxtDate(buffer.toString());
            try {
                String string = buffer.toString();
                Date parse = dateFormat.parse(string);
                item.setDate(parse);
            } catch (ParseException e) {
                log.error("转换后的日期格式错误: " + buffer.toString());
                e.printStackTrace();
            }
        } else if (item != null && qName.equalsIgnoreCase("guid")) {
            // 这就是网址
            item.setId(buffer.toString());
        } else if (qName.equalsIgnoreCase("item")){
            if (item.getId() == null){
                item.setId( item.getDescription().hashCode() + "");
            }
            list.add(item);
            item = null;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        buffer = new StringBuffer();
        // 解析到 xml文件的字符内容
        String str = new String(ch, start, length);
//        System.out.println("开始解析RSS数据xml元素内容" + "  str: " + str);
        buffer.append(str);
    }
}
